package com.c.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.c.constant.MessageConstant;
import com.c.dao.PermissionDao;
import com.c.model.PageResult;
import com.c.model.QueryPageBean;
import com.c.model.Result;
import com.c.pojo.Permission;
import com.c.service.PermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 权限管理
 */
@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    /**
     * 查询所有权限
     *
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    /**
     * 权限分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        //忽略空格查询条件
        if (queryPageBean.getQueryString() != null && queryPageBean.getQueryString().length() > 0) {
            queryString = queryPageBean.getQueryString().trim();// 去除查询条件首尾空格
        }
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增权限
     *
     * @param permission
     */
    @Override
    public Result add(Permission permission) {
        //先判断权限关键字是否存在（t_permission）
        Permission permission1 = permissionDao.findExist(permission);
        if (permission1 != null) {
            return new Result(false, "该权限关键字已经存在,无法创建");
        } else {
            permissionDao.add(permission);
            return new Result(true, MessageConstant.ADD_PERMISSION_SUCCESS);
        }
    }

    /**
     * 根据ID查询权限
     *
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    /**
     * 编辑权限
     *
     * @param permission
     */
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    /**
     * 根据ID删除权限
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断当前权限是否已经关联到角色
        long count = permissionDao.findCountByCheckPermissionId(id);
        if (count > 0) {
            return new Result(false, "此权限正在使用,无法删除");
        }
        permissionDao.deleteById(id);
        return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
    }

}
